const moment = require('moment');
const CacheFactory = require('./cacheFactory');

class SequenceUtil {
  static async getSequence(redisKey, num = 1) {
    const currentDay = moment().format('YYYYMMDD');
    redisKey = `${redisKey}${currentDay}`;
    const sequenceNum = await CacheFactory.getInstance().incrBy(redisKey, num);
    if (sequenceNum <= num) {
      CacheFactory.getInstance().expire(redisKey, 24 * 60 * 60 + 5 * 60)
        .catch((e) => {
          console.log(e);
          throw e;
        });
    }
    return `${currentDay}${sequenceNum.toString().padStart(4, '0')}`;
  }

  static async getWxPayId() {
    const payId = await SequenceUtil.getSequence('wx:pay:');
    return `wx_${payId}` + Math.floor(Math.random() * 100);
  }
  static async getWxRefundId() {
    const payId = await SequenceUtil.getSequence('wx:refund:');
    return `re_${payId}` + Math.floor(Math.random() * 100);
  }
}

module.exports = SequenceUtil;
